package com.sjzd.mail.receiver;

import com.rabbitmq.client.Channel;
import com.sjzd.server.constant.MailConstants;
import com.sjzd.server.pojo.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.Date;

@Component
public class MailReceiver {
    private static final Logger logger = LoggerFactory.getLogger(MailReceiver.class);

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private MailProperties mailProperties;



    @RabbitListener(queues = MailConstants.QUEUE_NAME)
    public void handler(Message message, Channel channel) {
        MessageHeaders headers = message.getHeaders();
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = (String) headers.get("spring_returned_message_correlation");
        // 设置邮件信息
        Employee emp = (Employee) message.getPayload();
        // 判断是否已经消费过该消息
        HashOperations hashOperations = redisTemplate.opsForHash();
        boolean exist = hashOperations.entries("mail").containsKey(msgId);
        try {
            if (exist) {
                /**
                 * 手动确认消息
                 * tag:消息序号
                 * multiple:是否多条
                 */
                channel.basicAck(tag, false);
                logger.info("消息早已被消费====>{}", tag);
                return;
            }
            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper msgHelper = new MimeMessageHelper(msg);

            msgHelper.setFrom(mailProperties.getUsername());
            msgHelper.setTo(emp.getEmail());
            msgHelper.setSubject("入职通知邮件");
            msgHelper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("name", emp.getName());
            context.setVariable("posName", emp.getPosition().getName());
            context.setVariable("joblevelName", emp.getJoblevel().getName());
            context.setVariable("departmentName", emp.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
            msgHelper.setText(mail, true);
            // 发送邮件
            javaMailSender.send(msg);
            logger.info("入职邮件发送成功======> {}", emp.getName());
            channel.basicAck(tag, false);
            hashOperations.put("mail", msgId, "ok");
        } catch (Exception e) {
            logger.error("入职邮件发送失败======> {}", emp.getName());
            e.printStackTrace();
        }
    }
}
